// import { PageContainer } from '@ant-design/pro-layout';
import { Button, Modal, Row, message } from 'antd';
import React, { useState } from 'react';
import MonacoEditor from '@uiw/react-monacoeditor';
import { editor } from 'monaco-editor';
import ProCard from '@ant-design/pro-card';
import ProTable, { ProColumns } from '@ant-design/pro-table';
import ReactDiffViewer from 'react-diff-viewer';
import { FormattedMessage, useIntl } from 'umi';
import { getMiddlewareCfgInfo } from '@/services/configserver/api';
import styles from './index.less';

const tableListDataSource: API.MiddlewareDeployListItem[] = [];
const middleware = ['Freeswitch', 'Rqlite', 'Redis', 'RabbitMQ', 'MySQL', 'Oracle', 'Kafka', 'Elasticsearch', 'Nacos', 'Monitor', 'Nginx'];

for (let i = 0; i < 11; i += 1) {
    tableListDataSource.push({
        id: i + 1,
        middleware: middleware[i % 10],
    });
}


const MiddlewareCfgDetails: React.FC<{}> = () => {
    const intl = useIntl();
    // 切换配置文件
    const [cfgInfo, setCfgInfo] = useState<string>('')


    // 显示配置文件的的内容
    const [code, setCode] = useState<string>('');
    // Diff窗口
    const [showDiffModal, handleDiffModal] = useState<boolean>(false);
    const editorDidMount = (editor: editor.IStandaloneCodeEditor) => {
        // console.log('editorDidMount', editor, monaco); // eslint-disable-line
        editor.focus();
    }

    //处理onrow点击事件
    const onCfgInfoRowClick = async (fields: API.MiddlewareDeployListItem) => {
        let type = fields.middleware;

        try {
            const result = await getMiddlewareCfgInfo({ type });
            //message.success('获取配置成功');
            console.log('HostsInfoList Event=onCfgInfoRowClick,value=', fields);
            console.log('HostsInfoList Event=获取配置成功');
            //利用JSON.stringify format json串，
            // 如果直接json直接显示，不用带上后面连个参数JSON.stringify(result.data)就可以了
            setCfgInfo(JSON.stringify(result.data, null, '\t'));
            return true;
        } catch (error) {
            message.error('添加失败');
            return false;
        }
    };

    // useEffect(() => {
    //    
    //     // eslint-disable-next-line react-hooks/exhaustive-deps
    // }, []);

    const columns: ProColumns<API.MiddlewareDeployListItem>[] = [
        {
            dataIndex: 'id',
            title: 'id',
        },
        {
            dataIndex: 'middleware',
            title: 'middleware',
        },
    ];

    return (
        // <PageContainer>
        <>
            <ProCard
                split="vertical"
                ghost gutter={8}
            >
                <ProCard
                    title={intl.formatMessage({
                        id: 'pages.MiddlewareCfgDetails.leftZoneTitle',
                        defaultMessage: 'middleware list',
                    })}
                    colSpan="30%"
                    headerBordered
                    bordered
                    className={styles.tableFrame}
                >
                    <ProTable<API.MiddlewareDeployListItem>
                        columns={columns}
                        style={{
                            height: 606
                        }}
                        request={(params, sorter, filter) => {
                            // 表单搜索项会从 params 传入，传递给后端接口。
                            console.log(params, sorter, filter);
                            return Promise.resolve({
                                data: tableListDataSource,
                                success: true,
                            });
                        }}
                        rowKey="id"
                        pagination={false}
                        // pagination={{
                        //     showQuickJumper: true,
                        // }}
                        toolBarRender={false}
                        search={false}
                        onRow={record => {
                            return {
                                onClick: (event) => {
                                    // 这里要处理在MonacoEditor里的value值了
                                    onCfgInfoRowClick(record);
                                }, // 点击行
                            };
                        }}
                    />
                </ProCard>

                <ProCard
                    title={intl.formatMessage({
                        id: 'pages.MiddlewareCfgDetails.rightZoneTitle',
                        defaultMessage: 'config info',
                    })}
                    bordered
                    headerBordered
                    className={styles.cardFrame}
                >
                    <Row
                        style={{
                            paddingBottom: 10
                        }}
                    >
                        <MonacoEditor
                            // ref={editorRef}
                            language='json'
                            height="500px"
                            width="100%"
                            value={cfgInfo}
                            editorDidMount={(editor) => editorDidMount(editor)}
                            onChange={async (value) => {
                                console.log("event = MiddlewareCfgDetails.MonacoEditor.onChange,newValue= ", value);
                                setCode(value);
                            }}
                            options={{
                                theme: "vs"
                            }}
                        />
                    </Row>
                    <Row>
                        <Button
                            type="primary"
                            key="primary"
                            onClick={() => {
                                handleDiffModal(true);
                            }}
                        >
                            <FormattedMessage
                                id="pages.MiddlewareCfgDetails.btn.updatecfg"
                                defaultMessage="update"
                            />
                        </Button>
                    </Row>

                </ProCard>
            </ProCard>
            <Modal
                title={intl.formatMessage({
                    id: 'pages.MiddlewareCfgDetails.diffModalTitle',
                    defaultMessage: 'Diff',
                })}
                visible={showDiffModal}
                width={1200}
                bodyStyle={{
                    padding: '10px',
                }}
                onOk={() => {
                    handleDiffModal(false);
                }}
                onCancel={() => {
                    handleDiffModal(false);
                }}
            >
                <ReactDiffViewer
                    oldValue={cfgInfo}
                    newValue={code}
                    splitView={true}
                    showDiffOnly={true}
                    extraLinesSurroundingDiff={3}
                />
            </Modal>
        </>
        // </PageContainer >
    );
};

export default MiddlewareCfgDetails;
